<?php
namespace App\Console\Commands;
use App\Constant\Enum;
use App\Models\Adreward;
use App\Models\AdrewardDetail;
use App\Models\GroupApply;
use App\Models\ReturnMoneyLog;
use App\Models\Setting;
use App\Models\User;
use App\Services\Wallet\UserWalletService;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ReturnMoneyCommand extends Command{

    protected $signature = "daemon:return_money";
    protected $description = "计算返佣";

    public function handle(){

        while(true){

            $return_money = ReturnMoneyLog::where('status',0)->orderBy('create_at','desc')->first();

            if($return_money){

                $group_apply = GroupApply::where('user_id',$return_money->uid)->first();
                $limit = intval($group_apply->price / $group_apply->days / $group_apply->amount);
                $exchangeRate = Setting::get('exchange_rate') ?? 1;
                $user = User::where('id',$return_money->uid)->first();

                $error_msg = "";
                $coins = intval($group_apply['amount'] * $exchangeRate);
                $money = $group_apply['amount'];

                if(ReturnMoneyLog::where('create_at','>',Carbon::today()->startOfDay())->where('status',1)->count() < $limit){

                    try{
                        DB::beginTransaction();
                        $reward = [
                            'user_id' => $group_apply->getAttribute('user_id'),
                            'amount' => $coins,
                            'real_amount' => $coins,
                            'real_money' => $money,
                            'user_money' => $money,
                            'received_at' => Carbon::now(),
                        ];
                        Adreward::query()->create($reward);

                        UserWalletService::income($user, $coins, Enum::WALLET_TYPE_REWARD);

                    }catch (\Exception $e){

                        $error_msg = $e->getMessage();
                        DB::rollBack();
                    }
                    DB::commit();
                }else{

                    $error_msg = "达到限额";
                }

                if($error_msg){

                    ReturnMoneyLog::where('id',$return_money->id)->update(['status'=>2,'msg'=>$error_msg]);
                }else{

                    ReturnMoneyLog::where('id',$return_money->id)->update(['status'=>1]);
                }

            }


            sleep(10);
        }
    }
}
